package com.example.home_model.details.customBehavior;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.example.home_model.R;

/**
 * 自定义behavior
 */
public class AnchorLinearBehavior extends CoordinatorLayout.Behavior<View> {
    private Context context;
    private int anchorId;

    public AnchorLinearBehavior(Context context, AttributeSet attrs) {
        this.context = context;
        TypedArray typedArray = this.context.obtainStyledAttributes(attrs, R.styleable.anchor_behavior, 0, 0);
        anchorId = typedArray.getResourceId(R.styleable.anchor_behavior_anchorId,0);
        typedArray.recycle();

    }

    @Override
    public boolean onMeasureChild(@NonNull CoordinatorLayout parent, @NonNull View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        View anchorView = parent.findViewById(anchorId);
        if (anchorView == null)
            return false;
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
        int topMargin = layoutParams.topMargin;
        int i = anchorView.getBottom() + topMargin;
        parent.onMeasureChild(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, i);
        return true;
    }

    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
        //获取锚点view
        View anchorView = parent.findViewById(anchorId);
        if (anchorView == null)
            return false;
        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) child.getLayoutParams();

        int topMargin = layoutParams.topMargin;
        int bottom = anchorView.getBottom();

        parent.onLayoutChild(child,layoutDirection);
        child.offsetTopAndBottom(topMargin+bottom);
        return true;
    }

    @Override
    public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
        return dependency.getId() == anchorId;
    }
}
